package com.stream.utils.schedule;

import com.stream.utils.RRException;
import com.stream.utils.SpringContextUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * Created by yebaokang on 2017/6/30.
 */
public class ScheduleRunnable implements Runnable {

    private Object target;
    private Method method;
    private String params;

    public ScheduleRunnable(String name, String methodName, String params) throws NoSuchMethodException {
        this.target = SpringContextUtils.getBean(name);
        this.params = params;

        if (StringUtils.isNotBlank(params)) {
            this.method = target.getClass().getDeclaredMethod(methodName, String.class);
        } else {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }

    @Override
    public void run() {
        ReflectionUtils.makeAccessible(method);
        try {
            if (StringUtils.isNotBlank(params)) {
                method.invoke(target, params);
            } else {
                method.invoke(target);
            }
        }
        /*catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }*/
        catch (Exception e) {
            throw new RRException( "执行定时任务失败." + System.lineSeparator()
                    + target.getClass().getName() + "."  + method.getName() + ":" + params );
        }
    }
}
